package com.lujieni.springbootemail.service;

import com.lujieni.springbootemail.dto.MailEntity;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.*;

/**
 * @Author：小鹿爱吃鱼
 * @Date: 2025/4/24 22:25
 * @Description:
 */
@Service
@RequiredArgsConstructor
public class MailService {

    private static final Logger log = LoggerFactory.getLogger(MailService.class);
    private final JavaMailSender javaMailSender;

    private final FreeMarkerConfigurer freeMarkerConfigurer;

    public void sendSimpleMail() {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("这是一封测试邮件1");
        message.setFrom("982584989@qq.com");
        message.setTo("703426078@qq.com");
        message.setSentDate(new Date());
        message.setText("这是测试邮件的正文");
        javaMailSender.send(message);
    }

    @Async("emailThreadPoolTaskExecutor")
    public void sendMailByFreemarker(MailEntity mailEntity) throws MessagingException, TemplateException, IOException {
        Map<String,Object> model = new HashMap<>();
        model.put("userName", "陆捷旎");
        // 往里面塞个List对象
        model.put("pets", Arrays.asList("dog","cat","tiger"));
        Template template = freeMarkerConfigurer.getConfiguration().getTemplate(mailEntity.getTemplateName());
        String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
        helper.setFrom(mailEntity.getFrom());
        helper.setTo(mailEntity.getTo()); //703426078@qq.com
        helper.setSentDate(new Date());
        helper.setText(text,  true);
        helper.setSubject(mailEntity.getSubject());
        javaMailSender.send(mimeMessage);
        log.info("sendMailByFreemarker done");
    }


}
